/**
 * Created by web_developer_02 on 2017/11/30
 */
import tool from './mUtil/tool'
import {
    baseUrl
} from './env'


export default async (url = '', data = {}, type = 'POST', method = 'fetch') => {

    function convertData(data) {
        if (typeof data === 'object') {
            let convertResult = "";
            for (let c in data) {
                convertResult += c + "=" + data[c] + "&";
            }
            convertResult = convertResult.substring(0, convertResult.length - 1);
            return convertResult;
        } else {
            return data;
        }
    }


    type = type.toUpperCase();
    url = baseUrl + url;

    if (type === 'GET') {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        });

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }
    if (window.fetch && method === 'fetch') {
        let requestConfig = {
            credentials: 'include',   //注释掉能fetch
            method: type,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded;application/json;charset=utf-8'
            },
            mode: "cors",
            cache: "force-cache"
        };

        if (type === 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: convertData(data)
            })
        }

        try {
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json();
            tool.log(responseJson);
            return responseJson;
        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if (type === 'POST') {
                sendData = convertData(data);
            }
            requestObj.withCredentials = true;
            requestObj.crossDomain = true;
            requestObj.open(type, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded;application/json;charset=utf-8");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState === 4) {
                    if (requestObj.status === 200) {
                        let obj = requestObj.response;
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        tool.log(obj);
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}


